package 力扣_树算法.遍历.层序遍历扩展;

import java.util.*;

/**199. 二叉树的右视图
 * @author zx
 * @create 2022-04-09 18:08
 */
public class 二叉树的右视图_199 {
    public List<Integer> rightSideView2(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root == null)  return res;
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int levelCount = queue.size();
            LinkedList<Integer> level = new LinkedList<>();
            for(int i = 0;i < levelCount;i++){
                TreeNode node = queue.poll();
                level.add(node.val);
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
            res.add(level.pollLast());
        }
        return res;
    }



    /**
     我们按照 [根结点 -> 右子树 -> 左子树] 的顺序访问,就可以保证每层都是最先访问最右边的节点的。
     (与先序遍历[根结点 -> 左子树 -> 右子树] 正好相反,先序遍历每层最先访问的是最左边的节点)
     */
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        helper(root,0,res);
        return res;
    }
    private void helper(TreeNode node,int level,List<Integer> res){
        if(node == null){
            return;
        }
        if(level == res.size()){
            res.add(node.val);
        }
        helper(node.right,level + 1,res);
        helper(node.left,level + 1,res);
    }

}
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
